<script setup lang="ts">
import { PropType, reactive, ref, unref, watch } from 'vue'
import { Descriptions } from '@/components/Descriptions'

import { ElButton, ElMessageBox } from 'element-plus'
import { ContentWrap } from '@/components/ContentWrap'
import { Table } from '@/components/Table'
import { useTable } from '@/hooks/web/useTableTest'
import { Dialog } from '@/components/Dialog'
import Edit from './Edit.vue'
import { CrudSchema, useCrudSchemas } from '@/hooks/web/useCrudSchemas'
import {
  sysDictDataListApi,
  sysDictDataAddApi,
  sysDictDataEditApi,
  sysDictDataDelApi
  // sysDictTypeListApi
} from '@/api/dict'
import { dictData } from '@/api/dict/types'

const props = defineProps({
  currentRow: {
    type: Object as PropType<Nullable<any>>,
    default: () => null
  },
  detailSchema: {
    type: Array as PropType<DescriptionsSchema[]>,
    default: () => []
  }
})

// 相关字典数据查询
/****************************** 相关组织列表 start ******************************/
const dictDataTable = useTable<
  {
    total: number
    list: any[]
  },
  any
>({
  getListApi: sysDictDataListApi,
  response: {
    data: 'data',
    count: 'count'
  }
})

const dictDataCrudSchemas = reactive<CrudSchema[]>([
  {
    field: 'label',
    label: '字典标签',
    search: {
      show: true
    }
  },
  {
    field: 'value',
    label: '字典键值',
    search: {
      show: true
    }
  },
  {
    field: 'disp_order',
    label: '排序'
  },
  {
    field: 'action',
    width: 160,
    fixed: 'right',
    label: '操作',
    form: {
      show: false
    },
    detail: {
      show: false
    }
  }
])
const dictDataRegister = dictDataTable.register
const dictDataTableObject = dictDataTable.tableObject
const dictDataMethods = dictDataTable.methods

const dictDataAllSchemas = useCrudSchemas(dictDataCrudSchemas).allSchemas

const dictDataGetList = dictDataMethods.getList

const actionType = ref('')
const dialogVisible = ref(false)
const dialogTitle = ref('')
const action = async (type: string, row: any = {}) => {
  actionType.value = type
  switch (type) {
    case 'add':
      dialogTitle.value = '新增'
      dictDataTableObject.currentRow = {}
      dialogVisible.value = true
      break
    case 'edit':
      dialogTitle.value = '编辑'
      dictDataTableObject.currentRow = row
      dialogVisible.value = true
      break
    case 'del':
      ElMessageBox.confirm('确定要删除这个角色吗？', '删除', {
        confirmButtonText: '确认',
        cancelButtonText: '取消',
        type: 'warning'
      })
        .then(() => {
          apiDel(row.dict_data_id)
        })
        .catch(() => {
          console.log('这里是取消confirm弹框')
        })
      break
    default:
      console.log('未知类型')
  }
}

const apiDel = async (dict_data_id) => {
  let delRes = await sysDictDataDelApi({ dict_data_id: dict_data_id })
    .catch(() => {})
    .finally(() => {
      // dictDataTableObject.loading = false
    })
  if (delRes) {
    dictDataGetList()
  }
}

const editRef = ref<ComponentRef<typeof Edit>>()
const loading = ref(false)
const save = async () => {
  const write = unref(editRef)
  switch (actionType.value) {
    case 'add':
      await write?.elFormRef?.validate(async (isValid) => {
        if (isValid) {
          loading.value = true
          const data = (await write?.getFormData()) as dictData
          const res = await sysDictDataAddApi({ ...data, ...newFixedSearch.value })
            .catch(() => {})
            .finally(() => {
              loading.value = false
            })
          if (res) {
            dialogVisible.value = false
            dictDataTableObject.currentPage = 1
            dictDataGetList()
          }
        }
      })
      break
    case 'edit':
      await write?.elFormRef?.validate(async (isValid) => {
        if (isValid) {
          loading.value = true
          const data = (await write?.getFormData()) as dictData
          const res = await sysDictDataEditApi({ ...data, ...newFixedSearch.value })
            .catch(() => {})
            .finally(() => {
              loading.value = false
            })
          if (res) {
            dialogVisible.value = false
            dictDataTableObject.currentPage = 1
            dictDataGetList()
          }
        }
      })
      break
    default:
      console.log('未知类型')
  }
}

/****************************** 相关组织列表 end ******************************/

/****************************** 监听设置固定条件 start ******************************/
const newFixedSearch = ref({})
watch(
  () => props.currentRow,
  (val: any) => {
    if (!val) return
    // 设置固定条件
    newFixedSearch.value = {
      dict_type: val.code
    }
    dictDataTableObject.fixedSearch = newFixedSearch.value
  },
  {
    deep: true,
    immediate: true
  }
)
/****************************** 监听设置固定条件 start ******************************/

/****************************** 初始化 start ******************************/
dictDataGetList() //查询相关组织列表
/****************************** 初始化 end ******************************/
</script>

<template>
  <Descriptions :schema="detailSchema" :data="currentRow || {}" />

  <div class="p-10px">
    <ContentWrap title="相关字典数据">
      <div class="mb-10px">
        <ElButton type="primary" @click="action('add', {})">新增</ElButton>
      </div>
      <Table
        v-model:pageSize="dictDataTableObject.pageSize"
        v-model:currentPage="dictDataTableObject.currentPage"
        :columns="dictDataAllSchemas.tableColumns"
        :data="dictDataTableObject.tableList"
        :loading="dictDataTableObject.loading"
        :pagination="{
          total: dictDataTableObject.count
        }"
        @register="dictDataRegister"
        :selection="false"
      >
        <template #action="{ row }">
          <ElButton type="primary" @click="action('edit', row)"> 编辑 </ElButton>
          <ElButton type="warning" @click="action('del', row)" title="删除"> 删除 </ElButton>
        </template>
      </Table>
    </ContentWrap>
  </div>

  <Dialog v-model="dialogVisible" :title="dialogTitle">
    <Edit
      v-if="actionType == 'edit' || actionType == 'add'"
      ref="editRef"
      :form-schema="dictDataAllSchemas.formSchema"
      :current-row="dictDataTableObject.currentRow"
    />
    <template #footer>
      <ElButton v-if="actionType !== 'detail'" type="primary" :loading="loading" @click="save">
        保存
      </ElButton>
      <ElButton @click="dialogVisible = false">关闭</ElButton>
    </template>
  </Dialog>
</template>
